package com.ruoyi.web.controller.demo;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.HttpClientSingleton;
import com.ruoyi.common.utils.RestTemplateUtils;
import com.ruoyi.common.utils.http.HttpClientUtil;
import com.ruoyi.common.utils.http.HttpHelper;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.uuid.UUID;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.compare.ComparableUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@RestController
@RequestMapping("/test")
@Anonymous
public class DemoTestController {

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private JedisPool jedisPool;

    private static final ObjectMapper objectMapper = new ObjectMapper();


    @PostMapping
    public AjaxResult post(String name,String desc) throws IOException {
        String url = "http://127.0.0.1:8002/test/req1";

        Map<String, Object> messageMap = new HashMap<>();
        messageMap.put("tid", IdUtils.fastUUID());
        messageMap.put("name",name);
        messageMap.put("desc","停车费系统发往中间系统 -----" + desc);

        System.err.println("我是医院停车费系统 开始发送数据:");
        System.out.println(messageMap);

        String resultJson = HttpClientUtil.sendPost(url, JSON.toJSONString(messageMap));

        return  AjaxResult.success(resultJson);

    }


    @PostMapping("/req1")
    @Anonymous
    public String post(@RequestBody Map<String, Object> map){
        System.err.println("接收到停车场系统发送的缴费订单" + map);

        String url = "http://127.0.0.1:8003/test/req2";

        Map<String, Object> messageMap = map;

        /**
         * todo 中间系统做的事情
         * 以下内容异步进行
         * 0. 处理数据
         * 1. 存redis
         * 2. 发送请求 收集请求的结果
         * 3. 异步存库(不需要结果)
         * 4. 返回
         */
        messageMap.put("desc",messageMap.get("desc") + "--追加 我是中间系统发送");

        ThreadPoolExecutor threadPoolExecutor = threadPoolTaskExecutor.getThreadPoolExecutor();


        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            try (Jedis jedis = jedisPool.getResource()) {
                jedis.setex((String) map.get("tid"), 60 ,JSON.toJSONString(messageMap));
                System.out.println("redis存库完成！！！");
            }catch (Exception e){
                System.err.println(e.getMessage());
            }
        }, threadPoolExecutor);


        CompletableFuture<String> requestFuture = CompletableFuture.supplyAsync(() -> {

            Map resultMap = null;

            try {
                String resultJson = HttpClientUtil.sendPost(url, JSON.toJSONString(messageMap));

                resultMap = objectMapper.readValue(resultJson, Map.class);

            }catch (Exception e){
                System.err.println(e.getMessage());
                return "缴费异常!";
            }

            if (200 == Integer.parseInt(resultMap.get("status").toString())) {
                return "成功";
            } else {
                return "缴费失败";
            }
        }, threadPoolExecutor);

        requestFuture.thenAcceptBoth(future,(result,e) -> {
            System.err.println("【请求结果返回】：" + result);

            // 模拟存库
            // 使用try-with-resources语句来确保Jedis实例在使用后正确关闭。
            try (Jedis jedis = jedisPool.getResource()) {
                String jsonData = jedis.get((String) map.get("tid"));

                Map parseObject = JSON.parseObject(jsonData, Map.class);

                System.err.println("最终的存库数据:"+ parseObject);

                Thread.sleep(1000);

            }catch (Exception ex) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(ex);
            }
        });

        // 返回请求结果，不阻塞主线程
        return requestFuture.join();
    }


    @PostMapping("/req2")
    @Anonymous
    public Map post2(@RequestBody Map<String, Object> map){
        System.err.println("我是光大银行-----接收到的数据为：");
        System.err.println(map);

        Map<String, Object> objectHashMap = new HashMap<>();
        objectHashMap.put("status",200);
        return objectHashMap;
    }
}
